﻿using System;
using System.Diagnostics;
using System.IO;

namespace BackupByFTP.LoggerFile
{
    public class Logger
    {
        public static string NowDate;
        /// <summary>
        /// 日志写入
        /// </summary>
        /// <param name="input"></param>
        public static void WriteLogFile(string input)
        {
            string logPath = Directory.GetCurrentDirectory() + "\\LogFile\\" + NowDate;
            //判断该路径下文件夹是否存在，不存在的情况下新建文件夹
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            //指定日志文件的目录
            string fname = logPath + "\\LogFile.txt";
            //定义文件信息对象
            FileInfo finfo = new FileInfo(fname);
            if (!finfo.Exists)
            {
                FileStream fs;
                fs = File.Create(fname);
                fs.Close();
                finfo = new FileInfo(fname);
            }

            //判断文件是否存在以及是否大于2K
            if (finfo.Length > 1024 * 1024 * 10)
            {
                //文件超过10MB则重命名
                File.Move(Directory.GetCurrentDirectory() + "\\LogFile.txt", Directory.GetCurrentDirectory() + DateTime.Now.TimeOfDay + "\\LogFile.txt");
            }
            //创建只写文件流
            using (FileStream fs = finfo.OpenWrite())
            {
                //根据上面创建的文件流创建写数据流
                StreamWriter w = new StreamWriter(fs);
                //设置写数据流的起始位置为文件流的末尾
                w.BaseStream.Seek(0, SeekOrigin.End);
                //写入“Log Entry : ”
                w.Write("Log Entry:");
                //写入当前系统时间并换行
                w.Write("{0}=={1}\n", DateTime.Now.ToLongTimeString(),
                    DateTime.Now.ToLongDateString());
                //写入日志内容并换行
                w.Write(input + "\n");
                //写入------------------------------------“并换行
                w.Write("------------------------------------\n");
                //清空缓冲区内容，并把缓冲区内容写入基础流
                w.Flush();
                //关闭写数据流
                w.Close();
            }
        }

        /// <summary>
        /// 日志读取
        /// </summary>
        public static void OpenLogFile()
        {
            string logPath = Directory.GetCurrentDirectory() + "\\LogFile";
            //string fname = logPath + "\\LogFile.txt";
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            //if (!File.Exists(fname))
            //{
            //    return;
            //}
            //Process.Start("explorer.exe", fname);
            Process.Start(logPath);
        }
    }
}
